package com.ht.api.call.func.impl.ad;

import java.util.ArrayList;
import java.util.List;

import javax.sql.DataSource;

import com.ht.api.bean.AjaxResult;
import com.ht.api.bean.LoginBean;
import com.ht.api.call.func.IFunctionCall;
import com.ht.api.db.Db;
import com.ht.api.db.DbList;
import com.ht.api.db.Entity;
import com.ht.api.db.StreamLoadConfig;
import com.ht.api.db.exception.HtException;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * 删除event_ad_config的前置函数
 * @author asq
 * @createTime 2025年3月20日 10:05:40
 */
@Slf4j
public class EventAdConfigDelBeforeFunctionCall implements IFunctionCall {

	@Override
	public String getName() {
		return "删除event_ad_config的前置函数";
	}

	@Override
	public JSONObject execute(LoginBean me, JSONObject param, AjaxResult result) {
		// 获取登陆用户的数据源
		DataSource ds = me.getDataSource();
		StreamLoadConfig config = me.getStreamLoadConfig();

		String configId = param.getStr("main_id");

		DbList eventPlanList = Db.createSqlParser("event_ad_plan_config").where("config_id", configId).query(ds);

		if (eventPlanList != null && eventPlanList.size() > 0) {
			List<String> eventPlanIds = new ArrayList<>();
			for (Entity entity : eventPlanList) {
				eventPlanIds.add(entity.getStr("main_id"));
			}

			Long userCount = Db.createSqlParser("ad_plan_user").where("source_id", "in", eventPlanIds).count(ds);
			if (userCount != null && userCount >0) {
				throw new HtException("事件配置已使用，不能删除，只能停用！");
			} else {
				List<Entity> dataList = new ArrayList<>();
				for (Entity eventPlan : eventPlanList) {
					Db.delete(ds, eventPlan);
					Db.delete(ds, Entity.create("ad_plan").set("main_id", eventPlan.getStr("plan_id")));
					Db.delete(ds, Entity.create("ad_campaign").set("main_id", eventPlan.getStr("campaign_id")));

					DbList itemList = Db.createSqlParser("ad_campaign_item").select("main_id").where("campaign_id", eventPlan.getStr("campaign_id")).query(ds);
					for (Entity entity : itemList) {
						entity.set("sys_deleted", 0);
						dataList.add(entity);
					}

				}
				Db.insertBatchWithStream(config, dataList);
			}
		}

		return JSONUtil.createObj();
	}
}
